<template> 
    <a-input-search v-model:value="state.roleSearchVal" style="margin-bottom: 8px" placeholder="请输入" />
    <a-list item-layout="horizontal" :data-source="state.roleDataTemp">
        <template #renderItem="{ item }">
            <a-list-item>
                <a-list-item-meta :description="item.code">
                    <template #title>
                        {{ item.name }}
                    </template>
                    <template #avatar>
                        <a-checkbox v-model:checked="item.checked" @change="onRoleCheck(item)" />
                    </template>
                </a-list-item-meta>
            </a-list-item>
        </template>
    </a-list></template>

<script setup lang="ts">
import { cloneDeep } from 'lodash';
import { reactive,watch } from 'vue';

const props = withDefaults(defineProps<{
    roleData:any[]
}>(),{
})
const emits = defineEmits<{
    (e:'change',data:any[]):void
}>()
const state = reactive<any>({
    roleSearchVal: "",
    roleDataTemp:cloneDeep(props.roleData), //副本
    showList: []
})


const onRoleCheck = (e: any) => {
    if (e.checked) {
        state.showList.push({
            id: e.id,
            name: e.name,
            type: 'role'
        })
    } else {
        state.showList = state.showList.filter((item: any) => item.id !== e.id)
    }
    emits('change', state.showList)
}

const setCheckedKeys = (keys:any[])=>{
    state.roleDataTemp.forEach((item:any)=>{
        if(keys.includes(item.id)){
            item.checked = true
            state.showList.push({
                id: item.id,
                name: item.name,
                type: 'role'
            })
        }
    })
    
}

// 角色搜素
watch(
    () => state.roleSearchVal,
    (val) => {
        if (val === '') {
            state.roleDataTemp = props.roleData
        } else {
            state.roleDataTemp = props.roleData.filter((item: any) => item.name.includes(val) || item.code.includes(val))
        }
    }
)

defineExpose({
    setCheckedKeys
})
</script>

<style lang='scss' scoped></style>